package com.lichong.quartzdemo.job.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lichong.quartzdemo.job.configure.ScheduleUtils;
import com.lichong.quartzdemo.job.entity.TbJob;
import com.lichong.quartzdemo.job.mapper.JobMapper;
import com.lichong.quartzdemo.job.service.IJobService;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 定时任务表 服务实现类
 * </p>
 *
 * @author lichong
 * @since 2020-07-30
 */
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, TbJob> implements IJobService {

    @Autowired
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器
     */
    @PostConstruct
    public void init() {
        List<TbJob> scheduleJobList = this.list();
        // 如果不存在，则创建
        scheduleJobList.forEach(scheduleJob -> {
            CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getJobId());
            if (cronTrigger == null) {
                ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
            } else {
                ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
            }
        });
    }
    @Override
    public void createJob(TbJob job) {
        job.setCreateTime(new Date());
        this.save(job);
        ScheduleUtils.createScheduleJob(scheduler, job);
    }

    @Override
    public void deleteJobs(String jobId) {
        ScheduleUtils.deleteScheduleJob(scheduler, Long.valueOf(jobId));
        this.baseMapper.deleteById(jobId);
    }

    @Override
    public void updateJob(TbJob job) {
        ScheduleUtils.updateScheduleJob(scheduler, job);
        this.baseMapper.updateById(job);
    }

    @Override
    public void run(String jobId) {
       ScheduleUtils.run(scheduler, this.getById(jobId));
    }

    @Override
    public void pause(String jobId) {
        ScheduleUtils.pauseJob(scheduler, Long.valueOf(jobId));
        TbJob job = new TbJob();
        job.setJobId(Long.valueOf(jobId));
        job.setStatus(TbJob.ScheduleStatus.PAUSE.getValue());
        this.baseMapper.updateById(job);
    }

    @Override
    public void resume(String jobId) {
        ScheduleUtils.resumeJob(scheduler, Long.valueOf(jobId));
        TbJob job = new TbJob();
        job.setJobId(Long.valueOf(jobId));
        job.setStatus(TbJob.ScheduleStatus.NORMAL.getValue());
        this.baseMapper.updateById(job);
    }
}
